package logic

import (
	"context"

	"github.com/comfygpt-backend-go/common/consts"
	"github.com/comfygpt-backend-go/common/utils"
	"github.com/comfygpt-backend-go/service/component-rpc/component"

	"github.com/comfygpt-backend-go/service/component-api/internal/svc"
	"github.com/comfygpt-backend-go/service/component-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListComponentsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListComponentsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListComponentsLogic {
	return &ListComponentsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListComponentsLogic) ListComponents(req *types.ListComponentsRequest) (resp *types.CommonResp, err error) {
	// 初始化响应
	resp = &types.CommonResp{
		Code:    int64(consts.SUCCESS),
		Message: consts.WrongMessageEn[consts.SUCCESS],
	}
	// 获取组件详情
	res, err := l.svcCtx.ComponentRpc.ListComponents(l.ctx, &component.ListComponentsRequest{Page: req.Page})
	if err != nil {
		resp.Code = int64(consts.SERVER_WRONG)
		resp.Message = consts.WrongMessageEn[consts.SERVER_WRONG]
		return
	}

	componentList := make([]*types.ComponentItem, 0)
	for _, compon := range res.Components {
		item := &types.ComponentItem{
			Id:          compon.Id,
			Name:        compon.Name,
			Description: compon.Description,
			Category:    compon.Category,
			Icon:        compon.Icon,
			Tags:        utils.ArrayToString(compon.Tags),
		}
		componentList = append(componentList, item)
	}
	resp.Data = componentList

	return
}
